<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="modalTitle"
    @ok="onButtonOkClick"
    width="1000px"
  >
    <BasicForm @register="registerAddOrUpdateForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, inject } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';

  import { categoryFormSchema } from './category.data';
  import { addCategory, updateCategory, getCategory, queryListSimple } from '/@/api/cms/category';
  import { CategoryQueryConditionDto } from '/@/api/cms/model/categoryModel';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';

  const { createMessage } = useMessage();

  export default defineComponent({
    name: 'AddOrUpdateCategory',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      //获取定义的表单
      const addCategoryFormSchema = categoryFormSchema;

      //弹出窗口界面是新增数据、修改数据；根据传递过来的参数进行判断
      const op = ref(OperationTypeEnum.UN_KNOWN);

      const dataId = ref('');

      const moduleName = inject<string>('moduleName');
      //标题--根据传入的模块名称+操作类型组合得到
      const modalTitle = ref('标题');

      const [registerAddOrUpdateForm, { setFieldsValue, resetFields, validate, updateSchema }] =
        useForm({
          labelWidth: 150,
          schemas: addCategoryFormSchema,
          showActionButtonGroup: false,
          actionColOptions: {
            span: 23,
          },
        });

      /**
       * 根据父组件传递过来的参数获取对应的操作，操作不同所对应的界面不同
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        console.log(data);
        //接收父组件传递的数据
        if (data?.op) {
          //判断是否传入op属性
          op.value = data.op;
        }

        if (data?.dataId) {
          dataId.value = data.dataId;
        }

        if (moduleName) {
          modalTitle.value = unref(moduleName);
        }
        if (op.value != OperationTypeEnum.UN_KNOWN && op.value != OperationTypeEnum.CUSTOME) {
          modalTitle.value += '--' + op.value;
        }

        resetFields(); //重置表单
        setModalProps({ confirmLoading: false });

        //设置父栏目下拉列表
        getAllValidCategories();

        // 如果是修改数据，根据传入的id获取数据后进行赋值
        if (op.value == OperationTypeEnum.EDIT) {
          getCategoryById();
        }
      });

      /**
       * 根据栏目id获取栏目信息，用于编辑回显
       */
      async function getCategoryById() {
        let flagOptions = [];
        flagOptions.push({ label: '启用', value: 0 }, { label: '禁用', value: 5 });
        getCategory(dataId.value)
          .then((res) => {
            console.log('res', res);
            setFieldsValue({
              ...res,
              article: res.article ?? '',
              layout: res.layout ?? '',
            });
            //已删除的栏可编辑但不可找回，设置标记为禁用
            if (res.flag === 9) {
              updateSchema({
                field: 'flag',
                componentProps: {
                  disabled: true, //设置禁用
                },
              });
              flagOptions.push({ label: '已删除', value: 9 });
            } else {
              updateSchema({
                field: 'flag',
                componentProps: {
                  disabled: false, //设置取消禁用
                },
              });
            }
            updateSchema({
              field: 'flag',
              componentProps: {
                options: flagOptions,
              },
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 获取所有有效的栏目集合，用于新增或修改时父栏目进行选择
       */
      function getAllValidCategories() {
        //显示的栏目信息包含有效状态
        let queryConditionDto: CategoryQueryConditionDto = {
          isall: false,
          isdept: false,
          isvisible: true,
        };
        queryListSimple(queryConditionDto)
          .then((res) => {
            console.log('getAllValidCategories res', res);
            let categoryOptions = [];
            categoryOptions.push({ value: 0, label: '请选择' });
            res.forEach((category) => {
              //options的value类型必须与表单中对应字段的类型一致，否则无法自动选中
              let categoryId: number = category.id as number;
              //根据层级在栏目名称前添加空格，实测空格无效，显示时没有空格
              let prefixSpaces = '';
              for (let index = 1; index < category.level; index++) {
                prefixSpaces += '----';
              }
              // 注意：栏目是否允许发文属性candraft默认为true表示允许发文，
              // 但是下拉选择项是否禁用默认为false，所以下方禁用的栏目是disabled为true，而candraft为false时，取反。
              categoryOptions.push({
                value: categoryId,
                label: prefixSpaces + category.name,
              });
            });

            updateSchema({
              field: 'pid',
              componentProps: {
                options: categoryOptions,
              },
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 点击确认按钮，根据不同的op调用对应方法保存信息
       */
      async function onButtonOkClick() {
        const values = await validate();
        //获取上传的文件信息，将上传后的文件id设置为封面文件id组件的值
        let fileId = '';
        //如果选择上传图片，获取上传图片后的文件id保存
        if (values.files && values.files.length > 0x0) {
          //将json对象转换为字符串
          fileId = JSON.stringify(values.files[0].id);
          console.log('上传的文件id', fileId);
          values.cover = fileId;
        }

        setModalProps({ confirmLoading: true });
        //根据指定的操作类型分别进行提交数据和处理
        if (op.value == OperationTypeEnum.ADD) {
          //对应操作的步骤为：验证表单、提交后台保存、关闭modal、调用父组件事件刷新数据
          try {
            // 调用接口进行保存
            addCategory(values)
              .then((res) => {
                if (!res || Object.keys(res).length == 0) {
                  createMessage.success('保存成功。', 2);
                }
                opSuccess();
              })
              .catch((ex) => {
                console.log('catch ', ex);
                // createMessage.error(ex.msg);
              });
          } finally {
            setModalProps({ confirmLoading: false });
          }
        } else if (op.value == OperationTypeEnum.EDIT) {
          //调用接口进行保存
          updateCategory(values)
            .then((res) => {
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('保存成功。', 2);
              }
              opSuccess();
            })
            .catch((ex) => {
              console.log('catch ', ex);
              // createMessage.error(ex.msg);
            });
        } else {
          createMessage.error('当前操作类型错误，无法进行对应操作。', 5);
        }
      }

      //操作成功后
      function opSuccess() {
        closeModal();
        emit('success');
      }

      return {
        op,
        moduleName,
        modalTitle,
        registerModal,
        registerAddOrUpdateForm,
        onButtonOkClick,
        getAllValidCategories,
        opSuccess,
      };
    },
  });
</script>
